package uoc.biblioteca.mappings.dao;

// Generated 11/04/2011 14:10:24 by Hibernate Tools 3.2.1.GA

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import uoc.biblioteca.mappings.object.EstadoSolicitudVo;
import uoc.biblioteca.mappings.object.LlibreVo;
import uoc.biblioteca.mappings.object.RevistaVo;
import uoc.biblioteca.mappings.object.SolicitudLlibreVo;
import uoc.biblioteca.mappings.object.SolicitudRevistaVo;
import uoc.biblioteca.sessionFactory.HibernateSessionFactory;

/**
 * Home object for domain model class SolicitudRevista.
 * @see uoc.biblioteca.mappings.dao.SolicitudRevistaVo
 * @author Hibernate Tools
 */
public class SolicitudRevistaHome {

	private static final Log log = LogFactory
			.getLog(SolicitudRevistaHome.class);

	private final SessionFactory sessionFactory = null;

	public SolicitudRevistaVo findById(java.lang.Integer id) {
		log.debug("getting SolicitudRevistaVo instance with id: " + id);
		try {
			
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.clear();
			
			SolicitudRevistaVo instance = (SolicitudRevistaVo) session.get("uoc.biblioteca.mappings.object.SolicitudRevistaVo", id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
				instance.getRevista();
			}
			
			
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public void saveNew(SolicitudRevistaVo instance) {
		
		log.debug("save new SolicitudRevistaVo instance");
		
		try {
			
			Date dataNow = new Date();
			instance.setDataActualizacio(dataNow);
			
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();
			
			session.clear();
			
			tx = session.beginTransaction();
			
			session.saveOrUpdate(instance);
			
			tx.commit();
			session.close();
			
			log.debug("saveNew successful");
			
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public void update(SolicitudRevistaVo instance) {
		
		log.debug("save new SolicitudRevistaVo instance");
		
		try {
			
			Date dataNow = new Date();
			instance.setDataActualizacio(dataNow);
			
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();
			
			tx = session.beginTransaction();
			
			session.clear();
			
			session.update(instance);
			
			tx.commit();
			session.close();
			
			log.debug("saveNew successful");
			
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public SolicitudRevistaVo[] getAllSolicitudsRevista(String idSolicitud,Integer idUser) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where c.user.id = "+idUser;
			
			if(idSolicitud!=null){
				hql+=" and c.estadoSolicitud.idEstadoSolicitud = "+idSolicitud;
			}
			hql += " order by c.dataCreacio desc";
			
			tx = session.beginTransaction();
			
			List tmpEvents = session.createQuery(hql).list();
			
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudRevistaVo[]) solicituds.toArray(new SolicitudRevistaVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los revistas solicitados noves para gestion
	public SolicitudRevistaVo[] getAllSolicitudsRevistaNoves() {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where c.estadoSolicitud.idEstadoSolicitud = 1";
			hql += " order by c.dataCreacio desc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudRevistaVo[]) solicituds.toArray(new SolicitudRevistaVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los revistas solicitados 
	public SolicitudRevistaVo[] getAllSolicitudsRevista() {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c";
			hql += " order by c.dataCreacio desc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudRevistaVo[]) solicituds.toArray(new SolicitudRevistaVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los revistas solicitados (historics)
	public SolicitudRevistaVo[] getAllSolicitudsRevistaByFiltres(String idEstado,Date dataInici,Date dataFi){
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where 1=1";
			if(idEstado!=null && !idEstado.equals("0")) {
				hql += " and c.estadoSolicitud.idEstadoSolicitud="+idEstado;
			}
			
			
			if(dataInici!=null){
				//hql += " and c.dataCreacio>"+dataInici;
				hql += " and c.dataCreacio>= :dataInici";
				
			}
			if(dataFi!=null){
				//hql += " and c.dataCreacio<"+dataFi;
				hql += " and c.dataCreacio<= :dataFi";
				
			}
			
			
			hql += " order by c.dataCreacio desc";
			
			List tmpEvents = null;
			
			if(dataInici!=null && dataFi ==null){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).list(); 
			}
			else if(dataFi!=null && dataInici ==null ){
				tmpEvents = session.createQuery(hql).setDate("dataFi", dataFi).list(); 
			}
			else if(dataInici !=null && dataFi!=null ){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).setDate("dataFi", dataFi).list(); 
			}
			else{
				tmpEvents = session.createQuery(hql).list();
			}
			
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudRevistaVo[]) solicituds.toArray(new SolicitudRevistaVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	//Mostrar todos los libros solicitados per filtres (mis solicituds)
	public SolicitudRevistaVo[] getAllSolicitudsRevistaByFiltres(String idEstado,Date dataInici,Date dataFi,Integer idUser,String nickUser,String titolFiltre) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			boolean where = false;
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where 1=1 ";
			
			//Si se filtra por el usuario (mis solicitudes)
			if(idUser!=null || nickUser!=null){
				
				if(titolFiltre!=null && !("").equals(titolFiltre)){
					hql+=" and c.revista.titol LIKE '%"+titolFiltre+"%'" ;
				}
				
				//hql+=" where (c.user.id = "+idUser +" or c.personaSolicitant='"+nameUser+ "') " ;
				if(idUser!=null){
					hql+=" and c.user.id = "+idUser ;
				}
				else if(nickUser!=null){
					hql+=" and c.personaSolicitant='"+nickUser+"' and c.user.nick!='"+nickUser+"'";
				}
				
				if(idEstado!=null && !idEstado.equals("0")) {
					hql += " and c.estadoSolicitud.idEstadoSolicitud="+idEstado;
				}
				
				
				if(dataInici!=null){
					//hql += " and c.dataCreacio>"+dataInici;
					hql += " and c.dataCreacio>= :dataInici";
					
				}
				if(dataFi!=null){
					//hql += " and c.dataCreacio<"+dataFi;
					hql += " and c.dataCreacio<= :dataFi";
					
				}
				
			}
			//Si no se filtra por el usuario
			else{
				
				if(titolFiltre!=null && !("").equals(titolFiltre)){
					hql+=" and c.revista.titol LIKE '%"+titolFiltre+"%'" ;
				}
				
				if(idEstado!=null && !idEstado.equals("0")) {
					hql += " and c.estadoSolicitud.idEstadoSolicitud="+idEstado;
				}
				
				
				if(dataInici!=null){
					//hql += " and c.dataCreacio>"+dataInici;
					hql += " and c.dataCreacio>= :dataInici";
					
				}
				if(dataFi!=null){
					//hql += " and c.dataCreacio<"+dataFi;
					hql += " and c.dataCreacio<= :dataFi";
					
				}
			}
			
			hql += " order by c.dataActualizacio desc";
			
			
			List tmpEvents = null;
			
			if(dataInici!=null && dataFi ==null){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).list(); 
			}
			else if(dataFi!=null && dataInici ==null ){
				tmpEvents = session.createQuery(hql).setDate("dataFi", dataFi).list(); 
			}
			else if(dataInici !=null && dataFi!=null ){
				tmpEvents = session.createQuery(hql).setDate("dataInici", dataInici).setDate("dataFi", dataFi).list(); 
			}
			else{
				tmpEvents = session.createQuery(hql).list();
			}
			
			//List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudRevistaVo[]) solicituds.toArray(new SolicitudRevistaVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public SolicitudRevistaVo duplicarSolicitud(SolicitudRevistaVo solRevista) {
		
		SolicitudRevistaVo solRevistaNew = new SolicitudRevistaVo();
		
		try{
			Date dateNow = new Date();
			
			if(solRevista!=null){
				solRevistaNew.setCentreResponsabilitat(solRevista.getCentreResponsabilitat());
				solRevistaNew.setDataActualizacio(dateNow);
				solRevistaNew.setDataCreacio(dateNow);
				
				EstadoSolicitudVo estado = new EstadoSolicitudVo();
				estado.setIdEstadoSolicitud(1);
				
				solRevistaNew.setEstadoSolicitud(estado);
				solRevistaNew.setNomGrupOrganitzatiu(solRevista.getNomGrupOrganitzatiu());
				solRevistaNew.setPersonaSolicitant(solRevista.getPersonaSolicitant());
				solRevistaNew.setRevista(solRevista.getRevista());
				solRevistaNew.setUser(solRevista.getUser());
				solRevistaNew.setValidadoGestor(0);
				solRevistaNew.setIdSolicitud(null);
				
				saveNew(solRevistaNew);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return solRevistaNew;
		
	}
	
	//Mostrar todos los libros duplicados por titol 
	public SolicitudRevistaVo[] getDuplicatsSolicitudsRevista(RevistaVo revista) {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where 1=1 " ;
			
			if(!("").equals(revista.getTitol())){
				hql += "and c.revista.titol = '"+revista.getTitol().replaceAll("'", "")+"'  ";
			}
			
			if(!("").equals(revista.getIssn())){
				hql += "or c.revista.issn ='"+revista.getIssn()+"' ";
			}
			
			hql += " order by c.dataCreacio asc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return (SolicitudRevistaVo[]) solicituds.toArray(new SolicitudRevistaVo[0]);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar todos los revistas para exportar a Millenium 
	public List getSolicitudsRevistaToMillenium() {
		
		/* will hold the books we are going to return later */
		try{
			List solicituds = new ArrayList();
		
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where c.enviadaMill=0 and c.validadoGestor=1 and c.tratadoMillenium = 0 and c.estadoSolicitud.idEstadoSolicitud=1";
			hql += " order by c.dataCreacio asc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				solicitudTemp.getEstadoSolicitud();
				solicituds.add(solicitudTemp);
			}
			tx.commit();
			
			return solicituds;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//Mostrar el numero de revistas sin ISSN para exportar a Millenium 
	public int comprobaSolicitudsRevistaToMilleniumSinIsbn() {
		
		/* will hold the books we are going to return later */
		try{
			int i=0;
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select c from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where c.enviadaMill=0 and c.validadoGestor=1 and c.tratadoMillenium = 0 and c.estadoSolicitud.idEstadoSolicitud=1";
			hql += " order by c.dataCreacio asc";
			
			List tmpEvents = session.createQuery(hql).list();
			for (Iterator iter = tmpEvents.iterator(); iter.hasNext();) {
				SolicitudRevistaVo solicitudTemp = (SolicitudRevistaVo) iter.next();
				solicitudTemp.getRevista();
				if(solicitudTemp.getRevista().getIssn()==null || solicitudTemp.getRevista().getIssn().equals("")){
					i++;
				}
			}
			tx.commit();
			
			return i;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	////Mostrar el numero de revistas para exportar a Millenium sin validar por el gestor 
	public int comprobaSolicitudsRevistaToMilleniumSinValidar() {
		
		/* will hold the books we are going to return later */
		try{
			Integer i=0;
			/* a Hibernate session */
			Session session = null;
			/* we always need a transaction */
			Transaction tx = null;
			/* get session of the current thread */
			session = HibernateSessionFactory.currentSession();

			session.flush();
			
			tx = session.beginTransaction();
			
			String hql="";
			hql="select count(c) from uoc.biblioteca.mappings.object.SolicitudRevistaVo as c where c.enviadaMill=0 and c.validadoGestor=0 and c.tratadoMillenium = 0 and c.estadoSolicitud.idEstadoSolicitud=1";
			hql += " order by c.dataCreacio asc";
			
			i = (Integer) session.createQuery(hql).uniqueResult();
			
			tx.commit();
			
			return i;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	
	
	
	
}
